package com.tedu.excelinportdamo.common.interceptor;

import com.tedu.excelinportdamo.common.result.JsonResult;
import com.tedu.excelinportdamo.common.result.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class FileImportInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取上传的文件
        MultipartFile file = (MultipartFile) request.getAttribute("file");
        log.info("文件上传开始检查");
        // 检查文件是否存在
        if (file == null || file.isEmpty()) {
            log.debug("文件为空");
            setResponse(response, new JsonResult(StatusCode.FILE_IS_NULL));
            return false;
        }

        // 检查文件格式
        String fileName = file.getOriginalFilename();
        if (fileName == null || !fileName.toLowerCase().endsWith(".xlsx")) {
            setResponse(response, new JsonResult(StatusCode.FILE_NOT_EXCEL));
            return false;
        }

        return true; // 返回true表示放行请求
    }

    private void setResponse(HttpServletResponse response, JsonResult result) throws Exception {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST); // 设置HTTP状态码为400 Bad Request
        response.setContentType("application/json;charset=UTF-8"); // 设置响应内容类型
        response.getWriter().write(result.toString());
    }
}
